from fastapi import APIRouter, Depends, HTTPException, status, Query, Request
from fastapi.security import APIKeyHeader
from app.config.config import API_KEY
from app.utils.logger import Logger
from app.utils.performance_monitor import get_performance_stats, clear_performance_records

# 创建日志记录器
logger = Logger("HTTPServer")

# 创建路由路由器
router = APIRouter()

# API密钥配置
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)

async def get_api_key(
    api_key: str = Depends(api_key_header), 
    api_key_query: str = Query(None, alias="api_key")
):
    """验证API密钥"""
    # 检查header和query参数中的API密钥
    final_api_key = api_key or api_key_query
    if final_api_key == API_KEY:
        return final_api_key
    else:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid API Key",
        )

async def get_ai_core(request: Request):
    """获取AI核心实例"""
    return request.app.state.ai_core

@router.get("/health")
async def health_check():
    """健康检查端点"""
    return {"status": "healthy"}

@router.get("/tools", dependencies=[Depends(get_api_key)])
async def get_tools(ai_core = Depends(get_ai_core)):
    """获取工具列表"""
    try:
        # 直接访问ai_core的tools属性，而不是调用get_tools方法
        tools = ai_core.tools
        # 转换工具列表为JSON序列化格式
        tools_data = []
        for tool in tools:
            # 检查tool是字典还是对象
            if isinstance(tool, dict):
                # 如果是字典，直接访问键值
                function_info = tool.get("function", {})
                tools_data.append({
                    "name": function_info.get("name", "Unknown"),
                    "description": function_info.get("description", ""),
                    "parameters": function_info.get("parameters", {})
                })
            else:
                # 如果是对象，访问属性
                tools_data.append({
                    "name": getattr(tool, 'name', 'Unknown'),
                    "description": getattr(tool, 'description', ''),
                    "parameters": getattr(tool, 'parameters', {}) if hasattr(tool, 'parameters') else {}
                })
        return {"tools": tools_data}
    except Exception as e:
        logger.error(f"获取工具列表时出错: {e}")
        return {"tools": []}

@router.get("/performance/stats", dependencies=[Depends(get_api_key)])
async def get_performance_statistics():
    """获取性能统计信息"""
    try:
        stats = get_performance_stats()
        logger.info(f"性能统计接口被调用，返回数据: {stats}")
        return {"status": "success", "data": stats}
    except Exception as e:
        logger.error(f"获取性能统计信息时出错: {e}")
        return {"status": "error", "message": str(e)}

@router.post("/performance/clear", dependencies=[Depends(get_api_key)])
async def clear_performance_statistics():
    """清空性能统计记录"""
    try:
        logger.info("收到清空性能统计记录请求")
        clear_performance_records()
        return {"status": "success", "message": "性能记录已清空"}
    except Exception as e:
        logger.error(f"清空性能统计记录时出错: {e}")
        return {"status": "error", "message": str(e)}